package com.dhcc.utils.objects;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;




public class DefaultObjectFactory implements ObjectFactory {
	private Map<String, Object> instances = new ConcurrentHashMap<String, Object>();
	public synchronized void registry(String name, Object bean){
		instances.put(name, bean);
	}
	public synchronized void registry(Object bean){
		instances.put(bean.toString(), bean);
	}
	
	@Override
	public Object getObjectByName(String name) throws NoSuchBeanException{
		Object target = null;
		if(name == null){
			throw new NullPointerException("name 不能为空");
		}
		target = instances.get(name);
		return target;
	}
	@Override
	public Object getObjectByType(Class<?> cls) throws NoSuchBeanException{
		Object target = null;
		Iterator<Object> values = instances.values().iterator();
		while(target==null && values.hasNext()){
			target = checkType(cls, values.next());
		}
		return target;
	}
	private Object checkType(Class<?> cls, Object instance){
		if(instance==null){
			return null;
		}
		if(cls==null){
			return instance;
		}
		if(cls.isInstance(instance)){
			return instance;
		}
		return null;
	}
}
